import {
  BadRequestException,
  Body,
  Controller,
  Delete,
  Get,
  HttpCode,
  HttpStatus,
  NotFoundException,
  Param,
  Post,
  Put,
  Req,
  ValidationPipe,
} from '@nestjs/common';
import { ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
import { Request } from 'express';
import { Order } from '../entities/order.entity';
import { CreateOrderDto, UpdateOrderDto } from './dto';
import { OrdersService } from './orders.service';

@ApiTags('orders')
@Controller('orders')
export class OrdersController {
  constructor(private readonly ordersService: OrdersService) {}

  @Get()
  @ApiOperation({ summary: '获取所有订单', description: '返回所有订单的列表' })
  @ApiResponse({ status: 200, description: '成功获取订单列表', type: [Order] })
  async findAll(): Promise<Order[]> {
    return this.ordersService.findAll();
  }

  @Get('user/:userId')
  @ApiOperation({
    summary: '获取用户的所有订单',
    description: '根据用户ID获取其所有订单',
  })
  @ApiParam({ name: 'userId', description: '用户ID' })
  @ApiResponse({ status: 200, description: '成功获取订单列表', type: [Order] })
  @ApiResponse({ status: 404, description: '用户不存在' })
  async findByUser(@Param('userId') userId: string): Promise<Order[]> {
    const id = parseInt(userId, 10);
    if (isNaN(id)) {
      throw new NotFoundException('用户ID必须是数字');
    }
    return this.ordersService.findByUser(id);
  }

  @Get(':id')
  @ApiOperation({ summary: '获取指定订单', description: '根据ID获取订单详情' })
  @ApiParam({ name: 'id', description: '订单ID' })
  @ApiResponse({ status: 200, description: '成功获取订单详情', type: Order })
  @ApiResponse({ status: 404, description: '订单不存在' })
  async findOne(@Param('id') id: string): Promise<Order> {
    const orderId = parseInt(id, 10);
    if (isNaN(orderId)) {
      throw new NotFoundException('订单ID必须是数字');
    }
    return this.ordersService.findOne(orderId);
  }

  @Post()
  @ApiOperation({ summary: '创建订单', description: '创建新的订单' })
  @ApiResponse({ status: 201, description: '成功创建订单', type: Order })
  @ApiResponse({ status: 400, description: '无效的请求数据' })
  @ApiResponse({ status: 404, description: '用户或房间不存在' })
  async create(@Body() createOrderDto: CreateOrderDto): Promise<Order> {
    console.log('收到创建订单请求:', JSON.stringify(createOrderDto));
    try {
      const result = await this.ordersService.create(createOrderDto);
      console.log('订单创建成功:', JSON.stringify(result));
      return result;
    } catch (error) {
      console.error(
        '订单创建失败:',
        error instanceof Error ? error.message : String(error),
      );
      throw error;
    }
  }

  @Put(':id')
  @ApiOperation({ summary: '更新订单', description: '更新指定ID的订单信息' })
  @ApiParam({ name: 'id', description: '订单ID' })
  @ApiResponse({ status: 200, description: '成功更新订单', type: Order })
  @ApiResponse({ status: 400, description: '无效的请求数据' })
  @ApiResponse({ status: 404, description: '订单不存在' })
  async update(
    @Param('id') id: string,
    @Body(ValidationPipe) updateOrderDto: UpdateOrderDto,
  ): Promise<Order> {
    const orderId = parseInt(id, 10);
    if (isNaN(orderId)) {
      throw new NotFoundException('订单ID必须是数字');
    }
    return this.ordersService.update(orderId, updateOrderDto);
  }

  @Delete(':id')
  @ApiOperation({ summary: '删除订单', description: '删除指定ID的订单' })
  @ApiParam({ name: 'id', description: '订单ID' })
  @ApiResponse({ status: 204, description: '成功删除订单' })
  @ApiResponse({ status: 404, description: '订单不存在' })
  @HttpCode(HttpStatus.NO_CONTENT)
  async remove(@Param('id') id: string): Promise<void> {
    const orderId = parseInt(id, 10);
    if (isNaN(orderId)) {
      throw new NotFoundException('订单ID必须是数字');
    }
    return this.ordersService.remove(orderId);
  }

  @Post('test-create')
  @ApiOperation({
    summary: '测试创建订单',
    description: '测试创建新的订单，绕过验证',
  })
  async testCreate(@Req() req: Request): Promise<any> {
    console.log('收到测试创建订单请求:', JSON.stringify(req.body));

    const rawData = req.body as {
      userId: number | string;
      roomID: number | string;
      checkInDate: string;
      checkOutDate: string;
    };

    try {
      const createOrderDto = {
        userId: Number(rawData.userId),
        roomID: Number(rawData.roomID),
        checkInDate: String(rawData.checkInDate),
        checkOutDate: String(rawData.checkOutDate),
      };

      console.log('处理后的订单数据:', JSON.stringify(createOrderDto));

      const result = await this.ordersService.create(createOrderDto);
      console.log('测试订单创建成功:', JSON.stringify(result));
      return {
        success: true,
        message: '测试订单创建成功',
        data: result,
      };
    } catch (error) {
      console.error(
        '测试订单创建失败:',
        error instanceof Error ? error.message : String(error),
      );
      return {
        success: false,
        message: error instanceof Error ? error.message : String(error),
        data: null,
      };
    }
  }

  @Post('direct-create')
  @ApiOperation({
    summary: '直接创建订单',
    description: '绕过DTO验证直接创建订单',
  })
  @ApiResponse({ status: 201, description: '成功创建订单', type: Order })
  async directCreate(@Req() req: Request): Promise<any> {
    console.log('收到直接创建订单请求:', JSON.stringify(req.body));

    const rawData = req.body as {
      userId: number | string;
      roomID: number | string;
      checkInDate: string;
      checkOutDate: string;
    };

    try {
      if (
        !rawData.userId ||
        !rawData.roomID ||
        !rawData.checkInDate ||
        !rawData.checkOutDate
      ) {
        throw new BadRequestException('缺少必要的字段');
      }

      // 手动构造订单对象
      const createOrderDto = {
        userId: Number(rawData.userId),
        roomID: Number(rawData.roomID),
        checkInDate: rawData.checkInDate,
        checkOutDate: rawData.checkOutDate,
      };

      console.log('处理后的订单数据:', JSON.stringify(createOrderDto));

      // 验证用户是否存在
      const user = await this.ordersService['usersService'].findOne(
        createOrderDto.userId,
      );
      if (!user) {
        throw new NotFoundException(`未找到ID为${createOrderDto.userId}的用户`);
      }

      // 验证房间是否存在
      const room = await this.ordersService['roomsService'].findOne(
        createOrderDto.roomID,
      );
      if (!room) {
        throw new NotFoundException(`未找到ID为${createOrderDto.roomID}的房间`);
      }

      // 验证日期是否合理
      const checkInDate = new Date(createOrderDto.checkInDate);
      const checkOutDate = new Date(createOrderDto.checkOutDate);

      console.log('处理日期 - 入住日期:', checkInDate);
      console.log('处理日期 - 离店日期:', checkOutDate);

      if (isNaN(checkInDate.getTime())) {
        throw new BadRequestException('请输入有效的入住日期');
      }

      if (isNaN(checkOutDate.getTime())) {
        throw new BadRequestException('请输入有效的离店日期');
      }

      if (checkOutDate <= checkInDate) {
        throw new BadRequestException('离店日期必须晚于入住日期');
      }

      // 创建订单
      const newOrder =
        this.ordersService['ordersRepository'].create(createOrderDto);
      const result =
        await this.ordersService['ordersRepository'].save(newOrder);

      console.log('订单创建成功:', JSON.stringify(result));
      return {
        success: true,
        message: '订单创建成功',
        data: result,
      };
    } catch (error) {
      console.error(
        '订单创建失败:',
        error instanceof Error ? error.message : String(error),
      );
      throw error;
    }
  }
}
